package main

import (
	"encoding/json"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
)

var DB *gorm.DB

type User struct {
	gorm.Model
	UserName string
	RoleName string
	Roles    []*Role `gorm:"many2many:user_roles;"`
}

type Role struct {
	gorm.Model
	RoleName    string
	RolePid     int
	RoleComment string
	Users       []*User `gorm:"many2many:user_roles;"`
}

func initDB() {
	dsn := "root:admin@tcp(101.43.132.73:30306)/test-casbin?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatal("Failed to connect to the database:", err)
	}
	DB = db
}

func migrate() {
	DB.AutoMigrate(&User{}, &Role{})
}

func createData() {
	user1 := &User{
		UserName: "User1",
		Roles: []*Role{
			{
				RoleName:    "Role0",
				RolePid:     0,
				RoleComment: "Comment0",
			},
			{
				RoleName:    "Role1",
				RolePid:     1,
				RoleComment: "Comment1",
			},
			{
				RoleName:    "Role2",
				RolePid:     2,
				RoleComment: "Comment2",
			},
		},
	}

	user2 := &User{
		UserName: "User2",
		Roles: []*Role{
			{
				RoleName:    "Role3",
				RolePid:     3,
				RoleComment: "Comment3",
			},
		},
	}

	DB.Create(user1)
	DB.Create(user2)
}

func main() {
	initDB()
	//defer DB.Close()

	migrate()

	createData()

	users := []User{
		//UserName: "User1",
	}
	//user := User{
	//	UserName: "User1",
	//}
	err := DB.Preload("Roles").Find(&users).Error
	if err != nil {
		log.Fatal("Failed to query data:", err)
	}

	res, err := json.Marshal(users)
	if err != nil {
		log.Fatal("Failed to marshal data:", err)
	}

	//user2 := &User{}
	//DB.Preload("Roles").Where("user_name = ?", "User2").Find(user2)
	//res, err := json.Marshal(user2)
	//if err != nil {
	//	panic(err)
	//}
	//fmt.Println("过滤2：", string(res))

	fmt.Println(string(res))
}
